The rules of operator precedence are complicated and can lead to errors. For this reason, parentheses should be used for clarification in complex
statements. However, this does not mean that parentheses should be gratuitously added around every operation.
This rule raises issues when &&
and ||
are used in combination, when assignment and equality or relational
operators are used together in a condition, and for other operator combinations according to the following table:
|
+ , - , * , / , % |
<< , >> , >>> |
& |
^ |
| |
+ , - , * , / , %
|
|
x |
x |
x |
x |
<< , >> , >>>
|
x |
|
x |
x |
x |
&
|
x |
x |
|
x |
x |
^
|
x |
x |
x |
|
x |
|
|
x |
x |
x |
x |
|
This rule also raises an issue when the "true" or "false" expression of a ternary operator is not trivial and not wrapped inside parentheses.
Noncompliant code example
x = a + b - c;
x = a + 1 << b; // Noncompliant
y = a == b ? a * 2 : a + b; // Noncompliant
if ( a > b || c < d || a == d) {...}
if ( a > b && c < d || a == b) {...} // Noncompliant
if (a = f(b,c) == 1) { ... } // Noncompliant; == evaluated first
Compliant solution
x = a + b - c;
x = (a + 1) << b;
y = a == b ? (a * 2) : (a + b);
if ( a > b || c < d || a == d) {...}
if ( (a > b && c < d) || a == b) {...}
if ( (a = f(b,c)) == 1) { ... }